package drds.server.datasource;

import java.util.ArrayList;
import java.util.concurrent.ConcurrentLinkedQueue;

public class ConnectionHolderQueue {
	private final ConcurrentLinkedQueue<IConnectionHolder> connectionHolderQueue = new ConcurrentLinkedQueue<IConnectionHolder>();

	public IConnectionHolder getConnectionHolder() {
		ConcurrentLinkedQueue<IConnectionHolder> connectionHolderQueue = this.connectionHolderQueue;
		IConnectionHolder connectionHolder = connectionHolderQueue.poll();
		if (connectionHolder != null && !connectionHolder.isClosedOrQuit()) {
			return connectionHolder;
		} else {
			if (connectionHolder != null && connectionHolder.isClosedOrQuit()) {
				// 需要进行资源回收
			}
			return null;
		}

	}

	public void removeConnectionHolder(IConnectionHolder connectionHolder) {
		if (!connectionHolderQueue.remove(connectionHolder)) {

		}
	}

	public boolean isSameConnectionHolder(IConnectionHolder connectionHolder) {
		if (connectionHolderQueue.contains(connectionHolder)) {
			return true;
		}
		return false;
	}

	public ConcurrentLinkedQueue<IConnectionHolder> getConnectionHolderQueue() {
		return connectionHolderQueue;
	}

	public ArrayList<IConnectionHolder> getIdleConnectionHolderListToClose(int count) {
		ArrayList<IConnectionHolder> connectionHolderList = new ArrayList<IConnectionHolder>(count);
		while (!connectionHolderQueue.isEmpty() && connectionHolderList.size() < count) {
			IConnectionHolder connectionHolder = connectionHolderQueue.poll();
			if (connectionHolder != null) {
				connectionHolderList.add(connectionHolder);
			}

		}
		return connectionHolderList;
	}

}
